﻿using System.Web.Mvc;
using mBlog.Models;
using mBlog.Services;
using mBlog.ViewModels;
using mBlog.Extensions;
using mBlog.Admin.ViewModels;
using System.Web.Helpers;

namespace mBlog.Admin.Controllers
{
    public class CategoryController : AdminBaseController
    {
        private ICategoryService categoryService;

        public CategoryController(ICategoryService catService)
        {
            this.categoryService = catService;
        }
       
        [HttpGet]
        public ActionResult Add()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Add(CategoryInput category)
        {
            var cat = categoryService.Single(category.UrlName);
            if (cat != null)
            {
                ModelState.AddModelError("Duplicated", "A category with same url name existed");
                return RedirectToAction("Add");
            }

            cat = category.MapTo<Category>();

            categoryService.Add(cat);
            TempData["Message"] = "Category Added Successfully";
            return RedirectToAction("List");
        }

        public ActionResult List()
        {
            var categories = categoryService.Get().MapTo<CategoryDetail>();
            return View(categories);
        }

        public JsonResult ListJson()
        {
            var categories = categoryService.Get().MapTo<CategoryDetail>();
            return Json(categories, JsonRequestBehavior.AllowGet);
        }

        [HttpGet]
        public ActionResult Edit(int id)
        {
            Category cat = categoryService.Single(id);
            return View(cat);
        }

        [HttpPost]
        public ActionResult Edit(Category category)
        {
            categoryService.Update(category);

            return RedirectToAction("Edit", new { id = category.ID });
        }

    }
}
